<!-- eslint-disable vue/no-mutating-props -->
<template>
  <card :showDivider="false">
    <div class="basic-info-wrapper">
      <a-descriptions :size="'medium'" :align="{ label: 'right' }">
        <a-descriptions-item label="订单编号（自有）">{{ orderDetail.orderCode || '-' }}</a-descriptions-item>
        <a-descriptions-item label="承租人">{{ orderDetail.memberStr || '-' }}</a-descriptions-item>
        <a-descriptions-item label="免押用户手机号">{{ orderDetail.freeMemberPhone || '-' }}</a-descriptions-item>
        <a-descriptions-item label="租车押金">{{
          orderDetail.carDepositAmount || orderDetail.carDepositAmount === 0 ? `${orderDetail.carDepositAmount} 元` : '-'
        }}</a-descriptions-item>
        <a-descriptions-item label="违章押金">{{
          orderDetail.illegalDepositAmount || orderDetail.illegalDepositAmount === 0 ? `${orderDetail.illegalDepositAmount} 元` : '-'
        }}</a-descriptions-item>
      </a-descriptions>
      <a-divider class="divider" />
      <a-descriptions :size="'medium'" :align="{ label: 'right' }">
        <a-descriptions-item label="剩余可操作金额">
          <template v-if="orderDetail.availableDepositAmount || orderDetail.availableDepositAmount === 0">
            <span class="blue">{{ orderDetail.availableDepositAmount || 0 }}</span> 元
          </template>
          <template v-else>-</template>
        </a-descriptions-item>
        <a-descriptions-item>
          <template #label> 押金预计解冻日期 </template>
          {{ orderDetail.planThawTime || '-' }}
          <a-tooltip position="top" mini>
            <icon-question-circle />
            <template #content>
              <p>{{ `1、未操作租车转违章前，押金最长冻结天数为${orderDetail.freezeDay}天；` }}</p>
              <p>{{
                `2、操作租车转违章后，未超过配置${orderDetail.freezeDay}天，押金最长冻结天数为${orderDetail.violationFreezeDay}天；`
              }}</p>
            </template>
          </a-tooltip>
        </a-descriptions-item>
        <a-descriptions-item label="已扣款次数">
          <div style="display: flex; align-items: center">
            <div class="tooltip-title" style="margin-right: 2px">
              <span class="blue">
                {{ orderDetail.cutPaymentNum || orderDetail.cutPaymentNum === 0 ? Number(orderDetail.cutPaymentNum) : '-' }}
              </span>
              次，剩余可扣款次数
              <span class="blue">
                {{ orderDetail.surplusNum || orderDetail.surplusNum === 0 ? Number(orderDetail.surplusNum) : '-' }}
              </span>
              次
            </div>
            <a-tooltip position="top" mini>
              <icon-question-circle />
              <template #content>
                <p>1、支付宝方每笔押金最多可扣款5次；</p>
                <p>2、已扣款次数仅统计扣款成功的次数；</p>
              </template>
            </a-tooltip>
          </div>
        </a-descriptions-item>
      </a-descriptions>
      <!-- 表格 -->
      <table-index class="insure-card-table" :table="tableCompulsory">
        <template #changeAmount="{ record }">
          <a-link v-if="record.operateType == 2" :hoverable="false" @click="toDetail(record)">
            <span>{{ `${record.changeDepositAmount <= 0 ? record.changeDepositAmount : `+${record.changeDepositAmount}`}` }}</span>
          </a-link>
          <div v-else>{{ `${record.changeDepositAmount <= 0 ? record.changeDepositAmount : `+${record.changeDepositAmount}`}` }}</div>
        </template>
      </table-index>
    </div>
    <!-- 扣款详情 -->
    <DeductionDetail ref="deductionDetailRef" />
    <!-- 转违章押金 -->
    <TransferDeposit ref="transferDepositRef" @ok="getDetail" />
    <!-- 全部解冻 -->
    <UnfreezeAll ref="unfreezeAllRef" @ok="getDetail" />
    <!-- 押金扣款 -->
    <DeductionDeposit ref="DeductionDepositRef" @ok="getDetail" />
  </card>
</template>

<script setup name="ShortOrderRele">
  import { useTable } from '@/hooks/table'
  import { ref, onMounted } from 'vue'
  import DeductionDetail from './deduction-detail.vue'
  import TransferDeposit from './transfer-deposit.vue'
  import UnfreezeAll from './unfreeze-all.vue'
  import DeductionDeposit from './deduct-deposit.vue'
  import { depositdetailV5, checkDeposit } from '@/api/order/sOrder'
  import { Message } from '@arco-design/web-vue'
  import dayjs from 'dayjs'

  const orderDetail = ref({})
  const props = defineProps({
    orderId: Number,
    //是否展示操作按钮
    showOperateBtn: {
      type: Boolean,
      default: true,
    },
  })

  const deductionDetailRef = ref()
  const transferDepositRef = ref()
  const unfreezeAllRef = ref()
  const DeductionDepositRef = ref()

  // table 配置
  const tableCompulsory = useTable({
    columns: [
      { title: '类型', dataIndex: 'operateTypeName', width: 120 },
      { title: '创建时间', dataIndex: 'createTime', width: 180 },
      { title: '流水单号', dataIndex: 'orderPayCode', width: 150 },
      { title: '变动金额', unit: '元', dataIndex: 'changeAmount', slotName: 'changeAmount', width: 120 },
      { title: '冻结金额', unit: '元', dataIndex: 'currentlyAvailableDepositAmount', width: 120 },
      { title: '状态', dataIndex: 'statusName', width: 80 },
      { title: '关联订单', dataIndex: 'orderCode', width: 170 },
      { title: '关联违章', dataIndex: 'violationCode', width: 150 },
      { title: '备注', dataIndex: 'remark' },
      { title: '操作人', dataIndex: 'createUserName' },
    ],
    operates: false,
    buttons: [
      {
        mode: 'import',
        label: '租车转违章',
        permission: 'svms:finance:deposit.rentaltoviolation',
        // 1 芝麻免押
        // 2 租车押金状态应收已收、应退未退
        // 3 未操作过租车转违章
        show: () =>
          props.showOperateBtn &&
          orderDetail.value.payType == 4 &&
          [30, 50].includes(orderDetail.value.carDepositStatus) &&
          !orderDetail.value.carRentalChangeViolation,
        method: async () => {
          checkDepositOperate('租车转违章').then((result) => {
            const { currentlyAvailableDepositAmount, receivedDepositAmount, violationFreezeDay } = result
            let carChangeViPlanThawTime = result.carChangeViPlanThawTime
            if (carChangeViPlanThawTime) {
              carChangeViPlanThawTime = dayjs(carChangeViPlanThawTime).format('YYYY-MM-DD')
            }
            transferDepositRef.value.show({
              // 租车押金id
              carDepositId: orderDetail.value.carDepositId,
              availableDepositAmount: currentlyAvailableDepositAmount,
              illegalDepositAmount: receivedDepositAmount,
              freezeDay: violationFreezeDay,
              carChangeViPlanThawTime: carChangeViPlanThawTime,
            })
          })
        },
      },
      {
        mode: 'import',
        label: '全部解冻',
        permission: 'svms:finance:deposit.allthaw',
        // 1 芝麻免押
        // 2 可用金额>0
        show: () => props.showOperateBtn && orderDetail.value.payType == 4 && Number(orderDetail.value.availableDepositAmount) > 0,
        method: async () => {
          checkDepositOperate('全部解冻').then((result) => {
            unfreezeAllRef.value.show({
              ...orderDetail.value,
              // 可用押金用接口返回的最新的
              availableDepositAmount: result.currentlyAvailableDepositAmount,
            })
          })
        },
      },
      {
        type: 'primary',
        label: '押金扣款',
        permission: 'svms:finance:deposit.deduction',
        // 1 芝麻免押
        // 2 可用金额>0
        show: () => props.showOperateBtn && orderDetail.value.payType == 4 && Number(orderDetail.value.availableDepositAmount) > 0,
        method: async () => {
          checkDepositOperate('押金扣款').then(() => {
            DeductionDepositRef.value.show(orderDetail.value.orderId)
          })
        },
      },
    ],
  })

  const checkDepositOperate = (name) => {
    return new Promise((resolve) => {
      const param = {
        id: props.orderId,
        type: name == '租车转违章' ? 1 : undefined,
      }
      checkDeposit(param).then((res) => {
        const { errorCode } = res.result
        if (errorCode === 888) {
          Message.error(`押金已不支持${name}`)
        } else if (errorCode === 999) {
          Message.error(`存在请求中的数据，暂不支持${name}`)
        } else {
          resolve(res.result)
        }
      })
    })
  }
  const toDetail = (record) => {
    deductionDetailRef.value.show(record)
  }
  onMounted(() => {
    tableCompulsory.tableLoading = true
    getDetail()
  })
  const getDetail = () => {
    depositdetailV5({
      orderId: props.orderId,
      orderType: 1, //1 短租 0 长租
    }).then((res) => {
      if (res.code == 200) {
        // 押金预计解冻日期
        const result = res.result
        let planThawTime = result.planThawTime
        if (planThawTime) {
          planThawTime = dayjs(planThawTime).format('YYYY-MM-DD')
        }
        // 创建时间
        const depositRecordList = result.depositRecordList
        if (depositRecordList && depositRecordList.length > 0) {
          depositRecordList.forEach((record) => {
            if (record.createTime) record.createTime = dayjs(record.createTime).format('YYYY-MM-DD HH:mm')
          })
        }
        result.planThawTime = planThawTime
        orderDetail.value = result
        tableCompulsory.tableLoading = false
        tableCompulsory.dataList = res.result.depositRecordList
      }
    })
  }
</script>

<style lang="less" scoped>
  .section-item {
    margin-bottom: 20px;
  }
  .tooltip-title {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #4e5969;
    text-align: left;
    font-style: normal;
    text-transform: none;
  }
  .insure-card-table {
    margin-top: 16px;
  }
  .blue {
    color: #1890ff;
  }
  .divider {
    margin: 16px 0;
  }
</style>
